package org.com.ashen.service.service.smssendlogmanage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.cookie.SM;
import org.com.ashen.client.service.ISMSSendLogService;
import org.com.ashen.common.common.HttpResult;
import org.com.ashen.common.common.smssendlog.SMSSendLogDTO;
import org.com.ashen.common.common.smssendlog.SMSSendLogReqDTO;
import org.com.ashen.dal.dataobject.*;
import org.com.ashen.service.dao.*;
import org.com.ashen.service.service.smssendlogmanage.sms.AliyunSmsUtil;
import org.com.ashen.service.service.smssendlogmanage.sms.YimeiSmsUtil;
import org.com.ashen.service.service.smssendlogmanage.sms.manage.dos.SmsResultDO;
import org.com.ashen.service.util.CodeUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service("sMSSendLogService")
public class SMSSendLogServiceImpl implements ISMSSendLogService {


    @Resource(name = "sMSBalanceDao")
    private SMSBalanceDao sMSBalanceDao;

    @Resource(name = "usersDao")
    private UsersDao usersDao;

    @Resource(name = "sMSPINDao")
    private SMSPINDao sMSPINDao;

    @Resource(name = "sMSSendLogDao")
    private SMSSendLogDao sMSSendLogDao;

    @Resource(name = "sMSSPTemplateDao")
    private SMSSPTemplateDao sMSSPTemplateDao;

    @Override
    @Transactional
    public HttpResult<SMSSendLogDTO> insert(SMSSendLogReqDTO record) {
        SMSSendLogDTO smsSendLogDTO = new SMSSendLogDTO();
        if(record == null){
            return HttpResult.failedResult(smsSendLogDTO,"传入内容不能为空");
        }
        String userId = record.getUserId();
        if(userId.equals("")){
            return HttpResult.failedResult(smsSendLogDTO,"用户不能为空");
        }
        Users users = usersDao.getUserByLoginId(userId);
        if(users==null){
            return HttpResult.failedResult(smsSendLogDTO,"用户不存在");
        }
        String APPSecret = users.getAppsecret();
        String privateAPPSecret = record.getPrivateAPPSecret();
        String statusTime = record.getSendTime();
        String tempAppSecret = CodeUtil.toStr(DigestUtils.md5(userId + APPSecret + statusTime));
        if(!tempAppSecret.equals(privateAPPSecret)){
            return HttpResult.failedResult(smsSendLogDTO,"用户验证不通过");
        }
        Date sendTime = null;
        try {
            sendTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(record.getSendTime());
        }catch (Exception e){}

        SMSSPTemplate smsspTemplate = sMSSPTemplateDao.selectByPrimaryKey(record.getTemplateCode());
        if(smsspTemplate==null){
            return HttpResult.failedResult(smsSendLogDTO,"模板不存在");
        }
        if(smsspTemplate.getTemplatetype() == 0 || smsspTemplate.getTemplatetype() == 2){
            SMSPIN smspin = new SMSPIN();
            SMSPIN smspin1 = sMSPINDao.selectMaxId();
            smspin.setId(smspin1.getId()+1);
            smspin.setCreatetime(sendTime);
            smspin.setUserid(record.getUserId());
            smspin.setStatus("0");
            smspin.setMobile(record.getMobile());
            String pin = Integer.toString(100000 + new Random().nextInt(900000));
            smspin.setPin(pin);
            System.out.println(JSON.toJSONString(smspin));
            sMSPINDao.insert(smspin);
            if(smsspTemplate.getTemplatetype() == 2) {
                record.setSmscontent("您的验证码是：" + pin);
            }else if(smsspTemplate.getTemplatetype() == 0){
                record.setSmscontent(pin);
            }
        }

        if(smsspTemplate.getTemplatetype() == 0 || smsspTemplate.getTemplatetype() == 1 || smsspTemplate.getTemplatetype() == 2 || smsspTemplate.getTemplatetype() == 3 ) {
            if (record.getSmscontent().equals("")) {
                return HttpResult.failedResult(smsSendLogDTO,"FAIL");
            }
            SMSBalance userIdBal = sMSBalanceDao.selectByPrimaryKey(record.getUserId());

            if(record.getMobiles() == null){
                if(userIdBal.getChargebalance().compareTo(new BigDecimal("10")) < 0){
                    return HttpResult.failedResult(smsSendLogDTO,"您的短信余额不足，请充值");
                }
            }else {
                if(userIdBal.getChargebalance().compareTo(new BigDecimal("10").multiply(new BigDecimal(record.getMobiles().length))) < 0){
                    return HttpResult.failedResult(smsSendLogDTO,"您的短信余额不足，请充值");
                }
            }


            String smsId = "";
            JSONArray smsIds = null;

            int smsCount = 0;
            if(smsspTemplate.getTemplatetype() == 2 || smsspTemplate.getTemplatetype() == 3){
                int strLen = CodeUtil.getStrlength("【"+record.getCustomSmsId()+"】"+record.getSmscontent());
                smsCount = strLen / 140 + 1;
            }else if(smsspTemplate.getTemplatetype() == 0 || smsspTemplate.getTemplatetype() == 1){
                if(smsspTemplate.getTemplatecontent().equals("")){
                    return HttpResult.failedResult(smsSendLogDTO,"您的短信模板没有编辑Templatecontent");
                }
                Scanner sc = new Scanner(smsspTemplate.getTemplatecontent());
                StringBuffer buf = new StringBuffer();
                try{
                    JSONObject smsContent = JSON.parseObject(record.getSmscontent());
                    Pattern p = Pattern.compile("[$][\\{]([^$]*?)[\\}]");
                    while (sc.hasNext()) {
                        Matcher m = p.matcher(sc.nextLine());
                        while (m.find()) { //查找并替换参数
                            //从map中根据key获取值
                            m.appendReplacement(buf, smsContent.get(m.group(1)) != null ? smsContent.get(m.group(1)).toString() : "");
                        }
                        m.appendTail(buf);
                    }
                }catch(Exception e){
                    e.printStackTrace();
                    return HttpResult.failedResult(smsSendLogDTO,"您的短信模板解析出错");
                }finally{
                    sc.close();
                }
                int strLen = CodeUtil.getStrlength("【"+record.getCustomSmsId()+"】"+buf.toString());
                smsCount = strLen / 140 + 1;
                if(smsspTemplate.getServiceprovider().equals("yimei")){
                    record.setSmscontent(buf.toString());
                }
            }else {
                return  HttpResult.failedResult(smsSendLogDTO,"您的短信模板没有编辑是否需要参数");
            }

            if(record.getMobiles() == null){
                if (smsspTemplate.getServiceprovider().equals("yimei")) {
                    record.setSmscontent("【"+record.getCustomSmsId()+"】"+record.getSmscontent());
                    smsId = YimeiSmsUtil.setSingleSms(record.getSmscontent(), null, null, record.getMobile());//短信内容请以商务约定的为准，如果已经在通道端绑定了签名，则无需在这里添加签名
                } else if (smsspTemplate.getServiceprovider().equals("aliyun")) {
                    smsId = AliyunSmsUtil.setSingleSms(record.getSmscontent(), record.getCustomSmsId(), record.getTemplateCode(), record.getMobile());//短信内容请以商务约定的为准，如果已经在通道端绑定了签名，则无需在这里添加签名
                }
            }else{
                if (smsspTemplate.getServiceprovider().equals("yimei")) {
                    record.setSmscontent("【"+record.getCustomSmsId()+"】"+record.getSmscontent());
                    smsIds = YimeiSmsUtil.setBatchOnlySms(record.getSmscontent(), null,  record.getMobiles());//短信内容请以商务约定的为准，如果已经在通道端绑定了签名，则无需在这里添加签名
                } else if (smsspTemplate.getServiceprovider().equals("aliyun")) {
                    smsId = AliyunSmsUtil.setSingleSms(record.getSmscontent(), record.getCustomSmsId(), record.getTemplateCode(), record.getMobile());//短信内容请以商务约定的为准，如果已经在通道端绑定了签名，则无需在这里添加签名
                }
            }

            SMSSendLog smsSendLog = new SMSSendLog();
            SMSSendLog smsSendLog1 = sMSSendLogDao.selectMaxId();
            smsSendLog.setId(smsSendLog1.getId() + 1);
            smsSendLog.setUserid(record.getUserId());
            smsSendLog.setMobile(record.getMobile());
            smsSendLog.setSmscontent(record.getSmscontent());
            smsSendLog.setSmstype(smsspTemplate.getTemplatetype()+"");
            smsSendLog.setSendtime(sendTime);
            smsSendLog.setCustomsmsid(record.getCustomSmsId());
            smsSendLog.setTemplatecode(record.getTemplateCode());
            smsSendLog.setSmsid(smsId);
            if (!smsId.equals("")) {
                smsSendLog.setPrice(new BigDecimal(10));
                smsSendLog.setStatus("SUCCESS");
                sMSSendLogDao.insert(smsSendLog);

                SMSBalance smsBalance = new SMSBalance();
                smsBalance.setUserid(record.getUserId());
                smsBalance.setUpdatetime(sendTime);
                BigDecimal balance = userIdBal.getChargebalance();
                smsBalance.setChargebalance(balance.subtract(new BigDecimal(10).multiply(new BigDecimal(smsCount))));
                sMSBalanceDao.updateByPrimaryKeySelective(smsBalance);

                smsSendLogDTO.setSmsid(smsId);
                smsSendLogDTO.setStatus("SUCCESS");
                return HttpResult.successResult(smsSendLogDTO);
            }else if(smsIds!=null){
                smsSendLog.setPrice(new BigDecimal(10));
                smsSendLog.setStatus("SUCCESS");
                sMSSendLogDao.insert(smsSendLog);

                SMSBalance smsBalance = new SMSBalance();
                smsBalance.setUserid(record.getUserId());
                smsBalance.setUpdatetime(sendTime);
                BigDecimal balance = userIdBal.getChargebalance();
                smsBalance.setChargebalance(balance.subtract(new BigDecimal(10).multiply(new BigDecimal(smsCount).multiply(new BigDecimal(record.getMobiles().length)))));
                sMSBalanceDao.updateByPrimaryKeySelective(smsBalance);

                smsSendLogDTO.setSmsids(smsIds);
                smsSendLogDTO.setStatus("SUCCESS");
                return HttpResult.successResult(smsSendLogDTO);
            }else{
                smsSendLog.setStatus("FAIL");
                sMSSendLogDao.insert(smsSendLog);
                return HttpResult.failedResult(smsSendLogDTO,"FAIL");
            }
        }

        return HttpResult.failedResult(smsSendLogDTO,"没有对应的短信类型");
    }




}
